// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: fengyang

#pragma once

#include <string>
#include <string_view>

#include <rapidjson/document.h>
#include <rapidjson/rapidjson.h>

#include "coin/proto/coin_market_enums.pb.h"
#include "coin2/base/conversion.h"
#include "coin2/exchange/base/feed/update.h"
#include "coin2/exchange/base/feed_util/book_builder.h"
#include "coin2/exchange/base/feed_util/trade.h"

namespace impl {
using coin2::exchange::base::market::ExchangeType;
using coin2::exchange::base::market::MarketType;
using namespace std::literals;

class DydxFuturesFeedUpdateParser {
 public:
  static void ParseBook(
      BookBuilder* book_builder_,
      const rapidjson::Document& doc,
      int64_t ts) {
    const std::string type = doc["type"].GetString();
    if (type == "subscribed") {
      ParseSnapshot(book_builder_, doc, ts);
    } else if (type == "channel_data") {
      ParseUpdate(book_builder_, doc, ts);
    } else {
      throw std::runtime_error("[DydxFutures] unknown book type: " + std::string(type));
    }
  }
  static void ParseUpdate(
      BookBuilder* book_builder_,
      const rapidjson::Document& doc,
      int64_t ts) {
    auto tx = book_builder_->NewTransaction(ts);

    const rapidjson::Value& data = doc["contents"];
    for (const auto& pq : data["asks"].GetArray()) {
      tx.UpdateAsk(
          stod(pq[0].GetString()),
          stod(pq[1].GetString()));
    }
    for (const auto& pq : data["bids"].GetArray()) {
      tx.UpdateBid(
          stod(pq[0].GetString()),
          stod(pq[1].GetString()));
    }
  }
  static void ParseSnapshot(
      BookBuilder* book_builder_,
      const rapidjson::Document& doc,
      int64_t ts) {
    auto tx = book_builder_->NewTransaction(ts);
    tx.Clear();

    const rapidjson::Value& data = doc["contents"];
    for (const auto& pq : data["asks"].GetArray()) {
      tx.UpdateAsk(
          stod(pq["price"].GetString()),
          stod(pq["size"].GetString()));
    }
    for (const auto& pq : data["bids"].GetArray()) {
      tx.UpdateBid(
          stod(pq["price"].GetString()),
          stod(pq["size"].GetString()));
    }
  }
  static void ParseTrade(const rapidjson::Value& trade_json, Trade* trade) {
    trade->timestamp = TimestampFromIso8601(trade_json["createdAt"].GetString());
    trade->price = stod(trade_json["price"].GetString());
    trade->fill_qty = stod(trade_json["size"].GetString());
    trade->side = ParseTradeSide(trade_json["side"].GetString());
  }
  static coin2::exchange::feed::TradeSide ParseTradeSide(std::string_view side) {
    if (side == "BUY") {
      return coin2::exchange::feed::TRADE_BUY_SIDE;
    } else if (side == "SELL") {
      return coin2::exchange::feed::TRADE_SELL_SIDE;
    } else {
      throw std::runtime_error("[DydxFutures] unknown side: " + std::string(side));
    }
  }

static fastfeed::proto::KlineInterval ParseKlineInterval(const std::string& period) {
    static std::map<std::string, fastfeed::proto::KlineInterval> interval_map = {
      {"1MIN", fastfeed::proto::KLINE_INTERVAL_1MIN},
      {"5MINS", fastfeed::proto::KLINE_INTERVAL_5MIN},
      {"15MINS", fastfeed::proto::KLINE_INTERVAL_15MIN},
      {"1HOUR", fastfeed::proto::KLINE_INTERVAL_1HOUR},
      {"1DAY", fastfeed::proto::KLINE_INTERVAL_1DAY}
    };
    auto iter = interval_map.find(period);
    if (iter == interval_map.end()) {
      NOTREACHED() << "Not support interval " << period;
      return fastfeed::proto::KLINE_INTERVAL_INVALID;
    }

    return iter->second;
  }

  static bool Parse1Kline(
      const rapidjson::Value& kline_data,
      Klines* klines,
      int64_t timestamp,
      fastfeed::proto::KlineInterval interval) {
    int64_t open_timestamp = TimestampFromIso8601(kline_data["startedAt"].GetString());
    auto result = klines->AddKline(open_timestamp);
    if (!result) return false;

    Kline* kline;
    bool freezed;
    std::tie(kline, freezed) = result.value();

    kline->open = stod(kline_data["open"].GetString());
    kline->high = stod(kline_data["high"].GetString());
    kline->low = stod(kline_data["low"].GetString());
    kline->close = stod(kline_data["close"].GetString());
    kline->volume = stod(kline_data["baseTokenVolume"].GetString());
    kline->turnover = stod(kline_data["usdVolume"].GetString());
    kline->timestamp = timestamp;
    kline->interval = interval;
    return freezed;
  }
};
}  // namespace impl

using impl::DydxFuturesFeedUpdateParser;
